package com.chinasofti.project.components;

import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import com.google.common.base.Preconditions;

/**
 * ServletContext启动时,加载配置数据
 * 
 * @author Lucas
 *
 */
@WebListener
public class ConfigLoadListener implements ServletContextListener {
	private Logger logger = LoggerFactory.getLogger(ConfigLoadListener.class);

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		logger.info("启动时加载配置文件");
		try {
			Properties p = PropertiesLoaderUtils.loadAllProperties("app.config.properties");
			String staticServerAddress = (String) p.get("static.server.address");
			Preconditions.checkNotNull(p.get("static.server.address"), "静态服务器地址为null");
			sce.getServletContext().setAttribute("staticServerAddress", staticServerAddress);
			logger.info("启动时加载配置文件成功");
		} catch (IOException e) {
			throw new RuntimeException("启动时读取系统配置文件失败", e);
		}
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {

	}

}
